<template>
  <div class="app-container">
    <section>
      <div>
        <span
          style="font-size:20px;font-weight: bold; display:block;margin-bottom: 20px;text-align: center;"
        >
          验货入库单
          <el-button size="mini" v-if="from.BillStatus==0" round>草稿</el-button>
          <el-button size="mini" v-if="from.BillStatus==1" round>已审核</el-button>
        </span>
      </div>
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form
          :inline="true"
          ref="from"
          :model="from"
          label-width="80px"
          class="demo-form-inline"
        >
          <div class="tabel">
            <el-form-item label="订单编号:">
              <span>{{from.OrderNo}}</span>
            </el-form-item>
            <el-form-item label="仓库" prop="BranchId">
              <el-select v-model="from.BranchId" filterable placeholder="请选择仓库">
                <el-option
                  v-for="item in StoreList"
                  :key="item.BranchId"
                  :label="item.BranchName"
                  :value="item.BranchId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="制单人:">
              <span>{{from.CreaterName}}</span>
            </el-form-item>
            <el-form-item label="制单时间:">
              <span>{{from.CreateDate}}</span>
            </el-form-item>
            <el-form-item label="摘要:">
              <el-input auto-complete="off" v-model="from.Summary" maxlength="12"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                v-if="from.BillStatus==0"
                type="primary"
                :loading="UpdataAndAddLoading"
                @click="UpdataAndAdd()"
                round
              >保存</el-button>
              <el-button
                v-if="from.BillStatus==0 && (this.$route.query.PRID || this.PRID )"
                type="success"
                @click="CheckPurchaseReceipt()"
                round
              >审核</el-button>
              <el-button
                v-if="from.BillStatus==1"
                type="danger"
                @click="UnCheckPurchaseReceipt()"
                round
              >反审</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
      <el-table
        :data="List"
        border
        :summary-method="getSummaries"
        show-summary
        height="600"
        :header-cell-style="{'background':'#F5F7FA','color':'#000',}"
      >
        <el-table-column prop="SKUName" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="SKUUnitNo" label="单位" align="center"></el-table-column>
        <el-table-column prop="Qty" label="入库数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              @change="handlesum(scope.$index,scope.row)"
              v-model="scope.row.Qty"
              size="mini"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="SKUInPrice" label="进价" align="center">
          <template slot-scope="scope">
            <el-input-number
              @change="handlesum(scope.$index,scope.row)"
              v-model="scope.row.SKUInPrice"
              size="mini"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="cgje" label="采购金额" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.cgje|numFilter}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Remark" label="备注" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.Remark" placeholder="请输入内容" maxlength="12"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="success" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </section>
  </div>
</template>

<script>
import {
  GetPurchaseOrdersAdd,
  GetPurchaseOrdersDetail,
  AddPurchaseReceipt,
  Gett_cg_PurchaseReceiptList,
  Gett_cg_PurchaseReceiptDetailList,
  UpPurchaseReceipt,
  CheckPurchaseReceipt,
  UnCheckPurchaseReceipt
} from "@/api/api";
import Config from "../../api/config";
export default {
  data() {
    return {
      UpdataAndAddLoading: false,
      skulist: [],
      editFormVisible: false,
      page: 1,
      pageSize: 10,
      total: 0,
      POID: "",
      PRID: "",
      from: {
        CreaterName: "",
        OrderNo: "",
        Creater: "",
        Creater2: "",
        CreateDate: "",
        SupplierName: "",
        Summary: "",
        BillStatus: "",
        SupplierId: "",
        BranchName: "",
        BranchId: 15
      },
      tempList: [
        {
          ProductId: "",
          Unit: "",
          Qty: "",
          Price: "",
          Summary: "",
          PurchaseMoney: ""
        }
      ],
      Id: "",
      List: [],
      jsonsprList: [],
      StoreList: [
        {
          BranchName: "总仓",
          BranchId: 15
        }
      ]
    };
  },
  filters: {
    numFilter(value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    }
  },
  created() {
    this.PRID = this.$route.query.PRID ? this.$route.query.PRID : this.PRID;
    this.getPurchaseOrders();
  },
  methods: {
    handleAllSum() {
      var self = this;
      this.List.forEach(function(row, index) {
        console.log("输出row", row);
        console.log("index", index);
        self.handlesum(index, row);
      });
    },
    handlesum: function(index, row) {
      if (!row) return;

      row.cgje = row.SKUInPrice * row.Qty;

      this.List[index] = row;
      console.log(this.List);
    },
    //删除列表·
    handleDelete(index, row) {
      this.List = this.List.filter(function(item) {
        return item != row;
        console.log("输出删除后的表格", this.List);
      });
    },
    //有值的时候为新增，无值的时候修改
    UpdataAndAdd() {
      this.PRID = this.$route.query.PRID ? this.$route.query.PRID : this.PRID;
      if (this.PRID === "") {
        this.AddPurchaseReceipt();
      } else {
        this.UpPurchaseReceipt();
        return;
      }
    },
    checkchange(IsGift) {
      this.tempList.IsGift = IsGift;
      console.log(this.tempList.IsGift);
    },

    getPurchaseOrders() {
      this.PRID = this.$route.query.PRID ? this.$route.query.PRID : this.PRID;
      if (this.PRID === "") {
        this.GetPurchaseOrdersDetail();
        this.GetPurchaseOrdersAdd();
      } else {
        this.Gett_cg_PurchaseReceiptDetailList();
        return;
      }
    },

    change(row) {
      this.row = row;
      console.log("输出当前的表格", row);
    },
    //审核采购订单
    CheckPurchaseReceipt() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRID ? this.$route.query.PRID : this.PRID
      };
      CheckPurchaseReceipt(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.Gett_cg_PurchaseReceiptDetailList();
        }
      });
    },

    //反审采购订单
    UnCheckPurchaseReceipt() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRID ? this.$route.query.PRID : this.PRID
      };
      UnCheckPurchaseReceipt(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.Gett_cg_PurchaseReceiptDetailList();
        }
      });
    },
    //获取采购表头(新增时)
    GetPurchaseOrdersAdd() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Exter: "RK"
      };
      GetPurchaseOrdersAdd(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log("获取验货表头", vdata);

          this.from.CreateDate = vdata.dateTime.substr(0, 10);
          this.from.CreaterName = vdata.CreaterName;
          this.from.Creater = vdata.Creater;
          this.from.OrderNo = vdata.OrderNo;
        }
      });
    },

    //获取商品以及表头
    GetPurchaseOrdersDetail() {
      console.log("打桩测试");
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        POId: this.$route.query.POID,
        Page: this.page,
        PageSize: this.pageSize
      };
      GetPurchaseOrdersDetail(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          self.List = vdata.DataList.filter(item => {
            item.Qty -= item.ActualQty
            return item.Qty > 0
          })
          this.from.CreateDate = self.List[0].CreateDate.substr(0, 10);
          this.from.Summary = self.List[0].Summary;
          this.from.SupplierName = self.List[0].SupplierName;
          this.handleAllSum();
        }
      });
    },

    //获取商品以及表头
    Gett_cg_PurchaseReceiptDetailList() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRID ? this.$route.query.PRID : this.PRID,
        Page: this.page,
        PageSize: this.pageSize
      };

      Gett_cg_PurchaseReceiptDetailList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          // debugger
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          self.List = vdata.DataList.filter(item => item.Qty !== 0)
          this.from.CreateDate = self.List[0].CreateDate.substr(0, 10);
          this.from.Summary = self.List[0].Summary;
          this.from.SupplierName = self.List[0].SupplierName;
          this.from.CreaterName = self.List[0].CreaterName;
          this.from.OrderNo = self.List[0].OrderNo;
          this.from.Remark = self.List[0].Remark;
          this.from.BillStatus = self.List[0].BillStatus;
          this.handleAllSum();
        }
      });
    },

    //修改采购列表
    UpPurchaseReceipt() {
      var self = this;
      self.tempList = [];
      for (var item in self.List) {
        var a = {
          ProductId: self.List[item].ProductId,
          Unit: self.List[item].SKUUnitNo,
          Qty: self.List[item].Qty,
          Price: self.List[item].SKUInPrice,
          PurchaseMoney: self.List[item].ADMoney,
          Remark: self.List[item].Remark
        };
        self.tempList.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        PRID: this.$route.query.PRID ? this.$route.query.PRID : this.PRID,
        BranchId: this.from.BranchId,
        Summary: this.from.Summary,
        tempList: self.tempList
      };
      UpPurchaseReceipt(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          this.UpdataAndAddLoading = false;
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success"
          });
          this.UpdataAndAddLoading = false;
        }
      });
    },

    //新增采购列表
    AddPurchaseReceipt() {
      this.UpdataAndAddLoading = true;
      var self = this;
      self.tempList = [];
      console.log("在新增里输出选择商品", this.List);
      for (var item in this.List) {
        var a = {
          ProductId: this.List[item].ProductId,
          Unit: this.List[item].SKUUnitNo,
          Qty: this.List[item].Qty,
          Price: this.List[item].SKUInPrice,
          PurchaseMoney: this.List[item].ADMoney,
          Remark: this.List[item].Remark
        };
        self.tempList.push(a);
      }
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        ParentId: this.$route.query.POID,
        OrderNo: this.from.OrderNo,
        Creater: this.from.Creater,
        BranchId: this.from.BranchId,
        Summary: this.from.Summary,
        tempList: self.tempList
      };
      AddPurchaseReceipt(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          this.UpdataAndAddLoading = false;
          return;
        } else {
          this.$message({
            message: res.data.Description,
            type: "success",
            duration: 1000,
            onClose: () => {
              self.onGett_cg_PurchaseReceiptList();
            }
          });
          this.UpdataAndAddLoading = false;
          // this.add();
        }
      });
    },

    //获取验收入库单列表*
    onGett_cg_PurchaseReceiptList() {
      console.log("打桩测试机");
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: 1,
        PageSize: 10,
        OrderNo: this.from.OrderNo
      };
      Gett_cg_PurchaseReceiptList(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          let vdata = JSON.parse(Base64.decode(res.data.Data));
          self.PRID = vdata.DataList[0].PRID;
          self.Gett_cg_PurchaseReceiptDetailList();
        }
      });
    },

    //求和
    getSummaries(param) {
      const { columns, data } = param;
      console.log("param", param);
      //console.log('data', data)
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index == 4) {
          sums[index] = 0;
          for (var item in data) {
            var row = data[item];

            row.cgje = 0;
            row.cgje = row.SKUInPrice * row.Qty;

            sums[index] += data[item].cgje;
          }
          sums[index] = sums[index].toFixed(2);
        }
        if (index == 2) {
          sums[index] = 0;
          for (var item in data) {
            sums[index] += data[item].Qty;
          }
          sums[index] = sums[index].toFixed(2);
        }
      });

      return sums;
    },

    add() {
      this.$router.push({
        path: "/Inspection/Inspectionlist"
      });
    }
  }
};
</script>
<style scoped>
.tabel {
  display: inline-block;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 90%;
}
.tabel .el-form-item {
  width: 30%;
  /* letter-spacing:8px; */
}
.tabel .el-button {
  padding: 0 20px;
  height: 30px;
}
.el-form-item--medium .el-form-item__content,
.el-form-item--medium .el-form-item__label {
  color: black;
}
span {
  color: black;
}
</style>